/* Copyright (c) 2010, David Kreuter. See LICENSE for more information */

#include "headers.h"

// Warning: The gl_id "1" is the 0th element in the arrays

mdl_mat *loaded_mat     [MAX_MATS];
static uint16 next_gl_id=0;

void load_mat(mdl_mat *m, tex* t){ // Internal Function, not in gl.h
	tex_tex *tt=t->tex+m->tex_id;
	if(next_gl_id==MAX_MATS){
		ERROR("Too many textures in scene\n");return;}
	m->gl_id=++next_gl_id;
	rgba *pixel=make_mat(m->tex_id,m->pal_id,m->repeat,t);
	if(!pixel){
		ERROR("Couldn't create material\n");return;}

	glBindTexture(GL_TEXTURE_2D,m->gl_id);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,
		tt->w*WRF(m->repeat),tt->h*HRF(m->repeat),
		0,GL_RGBA,GL_UNSIGNED_BYTE,(GLvoid *) pixel);

	free(pixel);
	loaded_mat[m->gl_id-1]=m;
}

void draw_cleanup(){
	for(uint16 i=0;i<next_gl_id;i++){
		loaded_mat[i]->gl_id=0;
		loaded_mat[i]=0;
	}
	next_gl_id=0;
}

void draw_map(map *m, tex *t, bmd **b, char halfsized){
	m->b->t=t;
	temporary_map_tex_fix(m); //WHAT?! FIXING EVERY FRAME?!
	draw_bmd(m->b);
	m->b->t=0;
	glPushMatrix();
	if(halfsized)glScalef(0.5f,0.5f,0.5f);
	glScalef(4.0f,4.0f,4.0f);
	if(b)for(uint32 i=0;i<m->num_ents;i++)
		draw_map_ent(m->ent+i,b);
	glPopMatrix();
}

void draw_map_ent(map_ent *e, bmd** buildings){
	glPushMatrix();
	glTranslatef(e->x,e->y,e->z);
	draw_bmd(buildings[e->b]);
	glPopMatrix();
}

void draw_bmd(bmd *b){
	if(!b)return;
	mdl *m=b->m;
	glScalef(m->scale,m->scale,m->scale);
	for(int a=0;a<m->num_layers;a++){
		mdl_layer *l=&m->layer[a];
		uint16 w,h;

		mdl_mat *mt=m->mat+l->mat_id;
		uint16 gl_id=mt->gl_id;
		if(b->t){
			tex_tex *tt=b->t->tex+mt->tex_id;
			uint8 repeat=mt->repeat;
			w=tt->w;h=tt->h;
			if(!mt->gl_id)load_mat(mt,b->t);
		}
		glBindTexture(GL_TEXTURE_2D, mt->gl_id);

		glBegin(GL_TRIANGLES);
		for(int b=0;b<l->num_tris;b++){
			mdl_vert *t=m->tri[b+l->tri_offset];
			for(int c=0;c<3;c++){
				glTexCoord2f(t[c].uv[0]/w,t[c].uv[1]/h);
				glColor3fv  (t[c].col);
				glVertex3fv (t[c].pos);
			}
		}
		glEnd();

		glBegin(GL_QUADS);
		for(int b=0;b<l->num_quads;b++){
			mdl_vert *t=m->quad[b+l->quad_offset];
			for(int c=0;c<4;c++){
				glTexCoord2f(t[c].uv[0]/w,t[c].uv[1]/h);
				glColor3fv  (t[c].col);
				glVertex3fv (t[c].pos);
			}
		}
		glEnd();
	}
}
